import React, { useContext, useState } from 'react';
import ReactDOM from 'react-dom';
const FormContext = React.createContext()
const ItemContext = React.createContext();
function Input() {
  let context = useContext(ItemContext)
  // let context2 = useContext(FormContext)
  console.log("input", context)
  let value = context.initialValues[context.name];
  let [val, setVal] = useState(value)
  return <>
    {context.label}<input type="text" value={val} onChange={(e) => {
      context.initialValues[context.name] = e.target.value;
      setVal(e.target.value)
    }} />
  </>
}
function Button(props) {
  let { onFinish } = useContext(ItemContext)
  return <>
    <button onClick={onFinish}>{props.children}</button>
  </>
}

function Form(props) {
  let { initialValues, onFinish, children } = props;
  return <FormContext.Provider value={{ initialValues, onFinish }}>
    {children}
  </FormContext.Provider>
}

function Item(props) {
  let context = useContext(FormContext)
  // console.log("item", context)
  let { children, label, name } = props;
  return <ItemContext.Provider value={{ label, name, ...context }}>
    {children}
  </ItemContext.Provider>
}
Form.Item = Item;
////==================================================================
class App extends React.Component {
  state = {
    initValue: {
      name: "珠峰",
      age: 12
    }
  }
  onFinish = () => {
    console.log("提交")
    console.log(this.state.initValue)
  }
  render() {
    return <div className=''>
      <Form
        initialValues={this.state.initValue}
        onFinish={this.onFinish}
      >
        <Form.Item
          label="用户名"
          name="name">
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="年龄"
          name="age">
          <Input></Input>
        </Form.Item>
        <Form.Item>
          <Button>提交</Button>
        </Form.Item>
      </Form>
    </div>;
  }
}

ReactDOM.render(<App />, document.getElementById('root'))